﻿namespace Hidistro.UI.Web.Admin.product
{
    using Hidistro.ControlPanel.Commodities;
    using Hidistro.ControlPanel.Store;
    using Hidistro.Core;
    using Hidistro.Entities.Commodities;
    using Hidistro.Entities.Store;
    using Hidistro.UI.ControlPanel.utility;
    using Ionic.Zip;
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Globalization;
    using System.IO;
    using System.Text;
    using System.Web.UI.WebControls;
    using System.Web;
    using Hidistro.Membership.Context;

    [PrivilegeCheck(Privilege.ProductBatchUpload)]
    public class ImportFromLocal : AdminPage
    {
        private readonly DirectoryInfo _baseDir = new DirectoryInfo(HttpContext.Current.Request.MapPath("~/storage/data/homemade"));
        private string _dataPath;
        private readonly Encoding _encoding = Encoding.UTF8;
        private DataTable _exportData = new DataTable();
        private DirectoryInfo _workDir;
        protected Button btnImport;
        protected Button btnUpload;
        private string csvPath = "";
        protected DropDownList dropFiles;
        protected FileUpload fileUploader;
        private string uploadPath = (HiContext.Current.GetstoragePath() + "/product");

        private void BindFiles()
        {
            this.dropFiles.Items.Clear();
            this.dropFiles.Items.Add(new ListItem("-请选择-", ""));
            DirectoryInfo info = new DirectoryInfo(this._dataPath);
            foreach (FileInfo info2 in info.GetFiles("*.zip", SearchOption.TopDirectoryOnly))
            {
                string name = info2.Name;
                this.dropFiles.Items.Add(new ListItem(name, name));
            }
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            string selectedValue = this.dropFiles.SelectedValue;
            selectedValue = Path.Combine(this._dataPath, selectedValue);
            if (!File.Exists(selectedValue))
            {
                this.ShowMsg("选择的数据包文件有问题！", false);
            }
            else
            {
                int num = 0;
                int num2 = 0;
                this.PrepareDataFiles(new object[] { selectedValue });
                List<List<string>> list = this.ReadCsv(this.csvPath, true, '\t', Encoding.GetEncoding("GB2312"));
                int num3 = 0;
                int count = list.Count;
                while (num3 < count)
                {
                    ProductInfo product = new ProductInfo();
                    try
                    {
                        List<string> list2 = list[num3];
                        if (list2[0x12] != "")
                        {
                            DataTable brandCategories = CatalogHelper.GetBrandCategories(list2[0x12]);
                            if (brandCategories.Rows.Count > 0)
                            {
                                product.BrandId = new int?(Convert.ToInt32(brandCategories.Rows[0]["BrandId"]));
                            }
                        }
                        if (list2[1] != "")
                        {
                            DataTable categoryes = CatalogHelper.GetCategoryes(list2[1]);
                            if (categoryes.Rows.Count > 0)
                            {
                                product.CategoryId = Convert.ToInt32(categoryes.Rows[0]["CategoryId"]);
                            }
                            else
                            {
                                product.CategoryId = 0;
                            }
                        }
                        else
                        {
                            product.CategoryId = 0;
                        }
                        if (list2[7] != "")
                        {
                            using (StreamReader reader = new StreamReader(Path.Combine(this.csvPath.Replace(".csv", ""), list2[7]), Encoding.GetEncoding("gb2312")))
                            {
                                product.Description = reader.ReadToEnd();
                            }
                        }
                        if (product.CategoryId > 0)
                        {
                            product.MainCategoryPath = CatalogHelper.GetCategory(product.CategoryId).Path + "|";
                        }
                        product.HasSKU = int.Parse(list2[0x13]) == 1;
                        product.ImageUrl1 = "";
                        product.ImageUrl2 = "";
                        product.ImageUrl3 = "";
                        product.ImageUrl4 = "";
                        product.ImageUrl5 = "";
                        if (list2[12] != "")
                        {
                            FileInfo info2 = new FileInfo(Path.Combine(this.csvPath.Replace(".csv", ""), list2[12]));
                            if (info2.Exists)
                            {
                                this.GetImg(info2.FullName, ref product, 1);
                            }
                        }
                        if (list2[13] != "")
                        {
                            FileInfo info3 = new FileInfo(Path.Combine(this.csvPath.Replace(".csv", ""), list2[13]));
                            if (info3.Exists)
                            {
                                this.GetImg(info3.FullName, ref product, 2);
                            }
                        }
                        if (list2[14] != "")
                        {
                            FileInfo info4 = new FileInfo(Path.Combine(this.csvPath.Replace(".csv", ""), list2[14]));
                            if (info4.Exists)
                            {
                                this.GetImg(info4.FullName, ref product, 3);
                            }
                        }
                        if (list2[15] != "")
                        {
                            FileInfo info5 = new FileInfo(Path.Combine(this.csvPath.Replace(".csv", ""), list2[15]));
                            if (info5.Exists)
                            {
                                this.GetImg(info5.FullName, ref product, 4);
                            }
                        }
                        if (list2[0x10] != "")
                        {
                            FileInfo info6 = new FileInfo(Path.Combine(this.csvPath.Replace(".csv", ""), list2[0x10]));
                            if (info6.Exists)
                            {
                                this.GetImg(info6.FullName, ref product, 5);
                            }
                        }
                        if (list2[0x11] != "")
                        {
                            product.MarketPrice = new decimal?(decimal.Parse(list2[0x11]));
                        }
                        if (list2[9] != "")
                        {
                            product.MetaDescription = list2[9];
                        }
                        if (list2[10] != "")
                        {
                            product.MetaKeywords = list2[10];
                        }
                        if (list2[4] != "")
                        {
                            product.ProductCode = list2[4];
                        }
                        product.ProductName = list2[3];
                        string str13 = list2[11];
                        if (str13 != null)
                        {
                            if (!(str13 == "出售中"))
                            {
                                if (str13 == "下架区")
                                {
                                    goto Label_04DA;
                                }
                                if (str13 == "仓库中")
                                {
                                    goto Label_04E4;
                                }
                            }
                            else
                            {
                                product.SaleStatus = ProductSaleStatus.OnSale;
                            }
                        }
                        goto Label_04EC;
                    Label_04DA:
                        product.SaleStatus = ProductSaleStatus.UnSale;
                        goto Label_04EC;
                    Label_04E4:
                        product.SaleStatus = ProductSaleStatus.OnStock;
                    Label_04EC:
                        if (list2[5] != "")
                        {
                            product.ShortDescription = list2[5];
                        }
                        if (list2[8] != "")
                        {
                            product.Title = list2[8];
                        }
                        if (list2[2] != "")
                        {
                            int typeId = ProductTypeHelper.GetTypeId(list2[2]);
                            if (typeId > 0)
                            {
                                product.TypeId = new int?(typeId);
                            }
                        }
                        if (!product.TypeId.HasValue)
                        {
                            product.HasSKU = false;
                        }
                        if (list2[6] != "")
                        {
                            product.Unit = list2[6];
                        }
                        Dictionary<string, SKUItem> skus = null;
                        Dictionary<int, IList<int>> attrs = null;
                        IList<int> tagsId = new List<int>();
                        if (list2[20] == "")
                        {
                            skus = new Dictionary<string, SKUItem>();
                            SKUItem item = new SKUItem {
                                SkuId = "0",
                                CostPrice = decimal.Parse(list2[0x18].Split(new char[] { ';' })[0]),
                                SalePrice = decimal.Parse(list2[0x19].Split(new char[] { ';' })[0]),
                                SKU = list2[0x15].Split(new char[] { ';' })[0],
                                Stock = int.Parse(list2[0x17].Split(new char[] { ';' })[0]),
                                Weight = decimal.Parse(list2[0x16].Split(new char[] { ';' })[0])
                            };
                            skus.Add(item.SKU, item);
                        }
                        else if (product.TypeId.HasValue)
                        {
                            skus = new Dictionary<string, SKUItem>();
                            int num6 = product.TypeId.Value;
                            if (product.HasSKU)
                            {
                                ProductTypeHelper.GetAttributes(num6, AttributeUseageMode.Choose);
                                string[] strArray = list2[20].Split(new char[] { ';' });
                                int length = strArray.Length;
                                for (int i = 0; i < length; i++)
                                {
                                    SKUItem item2 = new SKUItem {
                                        CostPrice = decimal.Parse(list2[0x18].Split(new char[] { ';' })[i]),
                                        SalePrice = decimal.Parse(list2[0x19].Split(new char[] { ';' })[i]),
                                        SKU = list2[0x15].Split(new char[] { ';' })[i],
                                        Stock = int.Parse(list2[0x17].Split(new char[] { ';' })[i]),
                                        Weight = decimal.Parse(list2[0x16].Split(new char[] { ';' })[i])
                                    };
                                    string str4 = strArray[i];
                                    Dictionary<int, int> dictionary3 = new Dictionary<int, int>();
                                    foreach (string str5 in str4.Split(new char[] { ',' }))
                                    {
                                        string specificationName = str5.Split(new char[] { ':' })[0];
                                        string valueStr = str5.Split(new char[] { ':' })[1];
                                        int specificationId = ProductTypeHelper.GetSpecificationId(num6, specificationName);
                                        if (specificationId > 0)
                                        {
                                            int specificationValueId = ProductTypeHelper.GetSpecificationValueId(specificationId, valueStr);
                                            if (specificationValueId > 0)
                                            {
                                                dictionary3.Add(specificationId, specificationValueId);
                                                continue;
                                            }
                                            product.HasSKU = false;
                                        }
                                        else
                                        {
                                            product.HasSKU = false;
                                        }
                                        break;
                                    }
                                    if (product.HasSKU && (dictionary3.Count > 0))
                                    {
                                        string str8 = "";
                                        foreach (KeyValuePair<int, int> pair in dictionary3)
                                        {
                                            item2.SkuItems.Add(pair.Key, pair.Value);
                                            str8 = str8 + pair.Value + "_";
                                        }
                                        item2.SkuId = str8.Substring(0, str8.Length - 1);
                                        skus.Add(item2.SKU, item2);
                                    }
                                }
                                if (skus.Count > 0)
                                {
                                    product.HasSKU = true;
                                }
                            }
                            else
                            {
                                SKUItem item3 = new SKUItem {
                                    SkuId = "0",
                                    CostPrice = decimal.Parse(list2[0x18].Split(new char[] { ';' })[0]),
                                    SalePrice = decimal.Parse(list2[0x19].Split(new char[] { ';' })[0]),
                                    SKU = list2[0x15].Split(new char[] { ';' })[0],
                                    Stock = int.Parse(list2[0x17].Split(new char[] { ';' })[0]),
                                    Weight = int.Parse(list2[0x16].Split(new char[] { ';' })[0])
                                };
                                skus.Add(item3.SKU, item3);
                            }
                        }
                        if ((list2[0x1a] != "") && product.TypeId.HasValue)
                        {
                            int num11 = product.TypeId.Value;
                            attrs = new Dictionary<int, IList<int>>();
                            IList<AttributeInfo> attributes = ProductTypeHelper.GetAttributes(num11, AttributeUseageMode.View);
                            foreach (AttributeInfo info7 in ProductTypeHelper.GetAttributes(num11, AttributeUseageMode.MultiView))
                            {
                                attributes.Add(info7);
                            }
                            foreach (string str9 in list2[0x1a].Split(new char[] { ',' }))
                            {
                                string str10 = str9.Split(new char[] { ':' })[0];
                                string str11 = str9.Split(new char[] { ':' })[1];
                                bool flag = false;
                                int attributeId = 0;
                                foreach (AttributeInfo info8 in attributes)
                                {
                                    if (info8.AttributeName.Equals(str10))
                                    {
                                        attributeId = info8.AttributeId;
                                        flag = true;
                                        break;
                                    }
                                }
                                if (flag)
                                {
                                    int num13 = ProductTypeHelper.GetSpecificationValueId(attributeId, str11);
                                    if (num13 > 0)
                                    {
                                        if (attrs.ContainsKey(attributeId))
                                        {
                                            attrs[attributeId].Add(num13);
                                        }
                                        else
                                        {
                                            List<int> list5 = new List<int> {
                                                num13
                                            };
                                            attrs.Add(attributeId, list5);
                                        }
                                    }
                                }
                            }
                        }
                        if (list2[0x1b] != "")
                        {
                            tagsId = new List<int>();
                            DataTable tags = CatalogHelper.GetTags();
                            foreach (string str12 in list2[0x1b].Split(new char[] { ',' }))
                            {
                                foreach (DataRow row in tags.Rows)
                                {
                                    if (row["TagName"].Equals(str12))
                                    {
                                        tagsId.Add(Convert.ToInt32(row["TagId"]));
                                        break;
                                    }
                                }
                            }
                        }
                        product.AddedDate = DateTime.Now;
                        switch (ProductHelper.AddProduct(product, skus, attrs, tagsId))
                        {
                            case ProductActionStatus.Success:
                                num++;
                                goto Label_0D7C;

                            case ProductActionStatus.AttributeError:
                                num2++;
                                goto Label_0D7C;

                            case ProductActionStatus.DuplicateName:
                                num2++;
                                goto Label_0D7C;

                            case ProductActionStatus.DuplicateSKU:
                                num2++;
                                goto Label_0D7C;

                            case ProductActionStatus.SKUError:
                                num2++;
                                goto Label_0D7C;
                        }
                        num2++;
                    }
                    catch
                    {
                        num2++;
                    }
                Label_0D7C:
                    num3++;
                }
                new DirectoryInfo(this.csvPath.Replace(".csv", "")).Delete(true);
                File.Delete(this.csvPath);
                File.Delete(selectedValue);
                this.BindFiles();
                if (num2 == 0)
                {
                    this.ShowMsg("此次商品批量导入操作已成功！", true);
                }
                else
                {
                    this.ShowMsg("此次商品批量导入操作," + num2 + "件商品导入失败！", false);
                }
            }
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (!this.fileUploader.HasFile)
            {
                this.ShowMsg("请先选择一个数据包文件", false);
            }
            else if ((this.fileUploader.PostedFile.ContentLength == 0) || (Path.GetExtension(this.fileUploader.FileName).Trim(new char[] { '.' }).ToLower() != "zip"))
            {
                this.ShowMsg("请上传正确的数据包文件", false);
            }
            else
            {
                string fileName = Path.GetFileName(this.fileUploader.PostedFile.FileName);
                this.fileUploader.PostedFile.SaveAs(Path.Combine(this._dataPath, fileName));
                this.BindFiles();
                this.dropFiles.SelectedValue = fileName;
            }
        }

        private void GetImg(string fileName, ref ProductInfo product, int index)
        {
            FileInfo info = new FileInfo(fileName);
            string str = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture) + Path.GetExtension(fileName);
            string str2 = this.uploadPath + "/images/" + str;
            string str3 = this.uploadPath + "/thumbs40/40_" + str;
            string str4 = this.uploadPath + "/thumbs60/60_" + str;
            string str5 = this.uploadPath + "/thumbs100/100_" + str;
            string str6 = this.uploadPath + "/thumbs160/160_" + str;
            string str7 = this.uploadPath + "/thumbs180/180_" + str;
            string str8 = this.uploadPath + "/thumbs220/220_" + str;
            string str9 = this.uploadPath + "/thumbs310/310_" + str;
            string str10 = this.uploadPath + "/thumbs410/410_" + str;
            info.CopyTo(base.Request.MapPath(Globals.ApplicationPath + str2));
            string sourceFilename = base.Request.MapPath(Globals.ApplicationPath + str2);
            ResourcesHelper.CreateThumbnail(sourceFilename, base.Request.MapPath(Globals.ApplicationPath + str3), 40, 40);
            ResourcesHelper.CreateThumbnail(sourceFilename, base.Request.MapPath(Globals.ApplicationPath + str4), 60, 60);
            ResourcesHelper.CreateThumbnail(sourceFilename, base.Request.MapPath(Globals.ApplicationPath + str5), 100, 100);
            ResourcesHelper.CreateThumbnail(sourceFilename, base.Request.MapPath(Globals.ApplicationPath + str6), 160, 160);
            ResourcesHelper.CreateThumbnail(sourceFilename, base.Request.MapPath(Globals.ApplicationPath + str7), 180, 180);
            ResourcesHelper.CreateThumbnail(sourceFilename, base.Request.MapPath(Globals.ApplicationPath + str8), 220, 220);
            ResourcesHelper.CreateThumbnail(sourceFilename, base.Request.MapPath(Globals.ApplicationPath + str9), 310, 310);
            ResourcesHelper.CreateThumbnail(sourceFilename, base.Request.MapPath(Globals.ApplicationPath + str10), 410, 410);
            if (index == 1)
            {
                product.ImageUrl1 = str2;
                product.ThumbnailUrl40 = str3;
                product.ThumbnailUrl60 = str4;
                product.ThumbnailUrl100 = str5;
                product.ThumbnailUrl160 = str6;
                product.ThumbnailUrl180 = str7;
                product.ThumbnailUrl220 = str8;
                product.ThumbnailUrl310 = str9;
                product.ThumbnailUrl410 = str10;
            }
            else
            {
                switch (index)
                {
                    case 2:
                        product.ImageUrl2 = str2;
                        return;

                    case 3:
                        product.ImageUrl3 = str2;
                        return;

                    case 4:
                        product.ImageUrl4 = str2;
                        return;

                    case 5:
                        product.ImageUrl5 = str2;
                        return;
                }
            }
        }

        protected override void OnInitComplete(EventArgs e)
        {
            base.OnInitComplete(e);
            this._dataPath = this.Page.Request.MapPath("~/storage/data/homemade");
            this.btnUpload.Click += new EventHandler(this.btnUpload_Click);
            this.btnImport.Click += new EventHandler(this.btnImport_Click);
            if (!this.Page.IsPostBack)
            {
                this.BindFiles();
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        public string PrepareDataFiles(params object[] initParams)
        {
            string str = (string) initParams[0];
            this._workDir = this._baseDir.CreateSubdirectory("product");
            using (ZipFile file = ZipFile.Read(Path.Combine(this._baseDir.FullName, str)))
            {
                foreach (ZipEntry entry in file)
                {
                    entry.Extract(this._workDir.FullName, ExtractExistingFileAction.OverwriteSilently);
                }
            }
            FileInfo[] files = this._workDir.GetFiles("*.csv", SearchOption.TopDirectoryOnly);
            int index = 0;
            while (index < files.Length)
            {
                FileInfo info = files[index];
                this.csvPath = info.FullName;
                break;
            }
            return this._workDir.FullName;
        }

        public List<List<string>> ReadCsv(string csvName, bool hasHeader, char colSplit, Encoding encoding)
        {
            List<List<string>> list = new List<List<string>>();
            string[] strArray = File.ReadAllLines(csvName, encoding);
            int index = 0;
            if (hasHeader)
            {
                index = 1;
            }
            while (index < strArray.Length)
            {
                string str = strArray[index];
                List<string> item = new List<string>();
                string[] strArray2 = str.Split(new char[] { colSplit });
                for (int i = 0; i < strArray2.Length; i++)
                {
                    item.Add(strArray2[i].Replace("\"", "").Replace("'", ""));
                }
                list.Add(item);
                index++;
            }
            return list;
        }
    }
}

